<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts'
import anlyze from '../../apis/anlyze.js'
import taskCotgary from '../../utils/taskCotgray.js'

const { t, locale } = useI18n()
const chart = ref(null)
let myChart = null
const loading = ref(false)
const error = ref(false)

const initChart = () => {
  if (myChart) {
    myChart.dispose()
  }
  
  // 确保DOM已经渲染
  if (chart.value) {
    myChart = echarts.init(chart.value)
    
    // 设置响应式
    const resizeHandler = () => {
      myChart && myChart.resize()
    }
    
    window.addEventListener('resize', resizeHandler)
    
    // 组件卸载时移除事件监听
    onUnmounted(() => {
      window.removeEventListener('resize', resizeHandler)
      myChart && myChart.dispose()
    })
  }
}

const fetchData = async () => {
  loading.value = true
  error.value = false
  
  try {
    const res = await anlyze.getTaskCategory()

    const chartData = res.map((count, index) => {
      const category = taskCotgary.find(item => item.value === String(index))
      return {
        name: category ? t(category.labelKey) : t('unknownCategory'),
        value: count
      }
    })

    // 过滤掉数量为0的类别，使图表更清晰
    const filteredData = chartData.filter(item => item.value > 0)

    // 确保图表已初始化
    if (!myChart) {
      initChart()
    }

    // 自定义颜色
    const colors = [
      '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', 
      '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#6e7074'
    ]

    const option = {
      title: {
        text: locale.value === 'en' ? t('taskTypeDistributionShort') : t('taskTypeDistribution'),
        left: 'center',
        top: 10,
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)',
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor: '#e6e9ed',
        borderWidth: 1,
        textStyle: {
          color: '#5e6d82'
        },
        extraCssText: 'box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);'
      },
      legend: {
        type: 'scroll',
        orient: 'horizontal', // 改为水平布局
        bottom: 10, // 移到底部
        left: 'center', // 居中对齐
        itemWidth: 14,
        itemHeight: 14,
        textStyle: {
          color: '#5e6d82',
          fontSize: 12
        },
        pageIconSize: 12,
        pageTextStyle: {
          color: '#5e6d82'
        },
        formatter: function(name) {
          // 根据语言调整图例文字长度限制
          const maxLength = locale.value === 'en' ? 8 : 12;
          return name.length > maxLength ? name.slice(0, maxLength - 2) + '...' : name;
        }
      },
      series: [
        {
          name: t('taskCategory'),
          type: 'pie',
          radius: '55%',
          center: ['50%', '45%'], // 调整圆饼图位置，为底部图例留出空间
          data: filteredData.sort((a, b) => b.value - a.value),
          roseType: 'radius',
          itemStyle: {
            borderRadius: 6,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}: {c}',
            fontSize: 12,
            color: '#5e6d82',
            alignTo: 'edge',
            edgeDistance: '10%',
            distanceToLabelLine: 5
          },
          labelLine: {
            show: true,
            length: 15,
            length2: 10,
            smooth: true
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            label: {
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function (idx) {
            return Math.random() * 200;
          }
        }
      ],
      color: colors,
      // 添加数据缩放功能
      dataZoom: [
        {
          type: 'inside',
          zoomOnMouseWheel: 'shift',
          moveOnMouseMove: true
        }
      ]
    }

    // 如果数据为空，显示无数据提示
    if (filteredData.length === 0) {
      option.graphic = [{
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: t('noMatchingData'),
          fill: '#999',
          fontSize: 16
        }
      }]
    }

    myChart.setOption(option)
    loading.value = false
  } catch (error) {
    console.error(t('dataLoadingFailed'), error)
    loading.value = false
    error.value = true
  }
}

// 监听语言变化，重新加载图表
watch(locale, () => {
  fetchData()
})

onMounted(() => {
  initChart()
  fetchData()
})
</script>

<template>
  <div class="chart-container">
    <div v-if="loading" class="loading-overlay">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <div class="loading-text">{{ $t('loading') }}</div>
    </div>
    
    <div v-if="error" class="error-overlay">
      <el-icon class="error-icon"><Warning /></el-icon>
      <div class="error-text">{{ $t('dataLoadingFailed') }}</div>
      <el-button size="small" @click="fetchData" class="retry-button">
        {{ $t('retryButton') }}
      </el-button>
    </div>
    
    <div ref="chart" class="chart"></div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 300px;
}

.loading-overlay, .error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
}

.loading-icon, .error-icon {
  font-size: 32px;
  margin-bottom: 12px;
  color: #909399;
}

.loading-text, .error-text {
  font-size: 14px;
  color: #606266;
}

.retry-button {
  margin-top: 12px;
  background: linear-gradient(135deg, #409eff, #53a8ff);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.retry-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

@media (max-width: 768px) {
  .chart {
    min-height: 250px;
  }
  
  .loading-icon, .error-icon {
    font-size: 24px;
  }
  
  .loading-text, .error-text {
    font-size: 12px;
  }
}
</style>
